<template>
	<div
		:class="[
			'app-editor-container',
			'app-mob-date__date-range',
			`app-mob-date-${name}`,
		]"
	>
		<AppMobDatePicker
			v-bind="$attrs"
			name="startdate"
			:value="startDatetime"
			:disabled="disabled"
			:readonly="readonly"
			:placeholder="startPlaceholder"
			@editor-event="DateChange"
		/>
		<span>~</span>
		<AppMobDatePicker
			v-bind="$attrs"
			name="enddate"
			:value="endDatetime"
			:disabled="disabled || !startDatetime"
			:readonly="readonly || !startDatetime"
			:placeholder="endPlaceholder"
			@editor-event="DateChange"
		/>
	</div>
</template>
<script lang="ts" setup>
import { IEvent, IParam } from '@/core';
import { dateRangeProps } from './date-range';
import { useEditorTypeParams } from "@/hooks/use-editor";
interface EditorEmit {
	(name: 'editor-event', value: IEvent<string>): void;
}
const props = defineProps(dateRangeProps);
const emit = defineEmits<EditorEmit>();
// 类型校验
const { validateConfig } = useEditorTypeParams();
validateConfig();
const attrs: IParam = useAttrs();
const valueSeparator: string = attrs.VALUESEPARATOR || ',';

const startName = computed(() => {
	if (props.valueItemNames) {
		return props.valueItemNames.split(',')[0];
	}
});
const endName = computed(() => {
	if (props.valueItemNames) {
		return props.valueItemNames.split(',')[1];
	}
});
const startDatetime = ref();
const endDatetime = ref();
watch(
	() => props.value,
	(newVal: any) => {
		if (newVal) {
			const items = newVal.split(valueSeparator);
			if (items.length === 2) {
				startDatetime.value = items[0];
				endDatetime.value = items[1];
			}
		}
	},
	{
		immediate: true,
	}
);
const verifyDate = () => {
	const start = new Date(startDatetime.value).getTime();
	const end = new Date(endDatetime.value).getTime();
	if (start >= end) {
		App.getNotificationHelper().warning(
			App.ts('common.daterange.warn', '结束时间需要大于起始值')
		);
		return false;
	}
	return true;
}

const DateChange = (params: IEvent<string>) => {
	const { name, data } = params;
	if (name === 'startdate') {
		startDatetime.value = data;
		if (endDatetime.value && !verifyDate()) {
			endDatetime.value = null;
			return null;
		}
	} else {
		endDatetime.value = data;
		if (startDatetime.value && !verifyDate()) {
			startDatetime.value = null;
			return null;
		}
	}
	const items = [startDatetime.value, endDatetime.value];
	emit('editor-event', {
		name: `${props.name}`,
		action: 'valueChange',
		data: items.join(valueSeparator),
	});
	if (startName.value && startDatetime.value) {
		emit('editor-event', {
			name: startName.value,
			action: 'valueChange',
			data: startDatetime.value.toString(),
		});
	}
	if (endName.value && endDatetime.value) {
		emit('editor-event', {
			name: endName.value,
			action: 'valueChange',
			data: endDatetime.value.toString(),
		});
	}
};
</script>
